﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using MySql.Data.MySqlClient;
using System.Data.Odbc;
using System.Collections.Specialized;

namespace EuroAudit
{
    public partial class StructEditor : System.Web.UI.Page
    {
        string[] VID = null;
        string[] NText = null;
        string[] VPRM = null;
        GlobalF GFunc = new GlobalF();

        protected void Page_Load(object sender, EventArgs e)
        {
            DataSet ds;
            string QString;
            DataSet dsUEB;
            string qsUEB = "";
            Button H;
            int UserEditBranch = 0;
            Boolean AllowEdit;

            //Table1.Rows[0].Cells[0].Text = "SIA TRIĀLS";
            TableRow NewRow = new TableRow();
            TableCell NewCell = new TableCell();
            /*NewCell.Text = "SIA TRIĀLS";
            NewCell.Font.Bold = true;
            NewCell.Font.Size = 18;
            NewCell.VerticalAlign = VerticalAlign.Middle;
            NewCell.HorizontalAlign = HorizontalAlign.Center;
            NewRow.Cells.Add(NewCell);
            tblSanDok.Rows.Add(NewRow);
            NewRow = new TableRow();
            NewCell = new TableCell();
            NewCell.Text = "INTRANET";
            NewCell.Font.Bold = true;
            NewCell.Font.Size = 18;
            NewCell.VerticalAlign = VerticalAlign.Middle;
            NewCell.HorizontalAlign = HorizontalAlign.Center;
            NewRow.Cells.Add(NewCell);
            tblSanDok.Rows.Add(NewRow);
            */


            NameValueCollection HRStr = Request.QueryString;
            //if (HRStr.GetValues("ViewParam") != null)
            //{
                VID = HRStr.GetValues("ViewID");
                VPRM = HRStr.GetValues("ViewParam");//DocType lauks
                //NText = HRStr.GetValues("NText");
                /////////////////////////////////////////////////////////////////////////////////////////////////////////
                //parametru UserEditBranch nedrīkst nodot QueryString'ā, pārbaude ir jāveic katrā DocList'a pieprasījumā/
                //int.TryParse(HRStr.GetValues("UserEditBranch")[0].ToString(),out UserEditBranch);                     /

                cmdNew.Visible = true;

                //lblSanDok.Text = "Saņemtie " + NText[0];
                //lblIzdDok.Text = "Nosūtītie " + NText[0];
                tblStruct.Rows.Clear();
                //}
                //Response.Write("ViewID=" + VID[0] + ", NodePath=" + NP[0]);
                //int CharNum = NText[0].Length + 2;
                if (Session["UserName"] == null || Session["UserName"].ToString() == "" || Session["UserName"].ToString() == "guest")
                {
                    //QString = "SELECT * FROM tcontent WHERE RecStatus=0 ORDER BY NodePath";
                    Response.Redirect("Login.aspx", true);
                    return;
                }
                else
                {
                    if (IsPostBack)
                    {
                        if (_RESULT.Text == "OKcmdDel")
                        {
                            cmdDel_Click(sender, e);
                            _RESULT.Text = "";
                        }
                    }
                    /*if (Session["IsAdmin"].ToString() == "1")
                    {
                        QString = "SELECT * FROM tcontent WHERE RecStatus ORDER BY NodePath";
                        UserEditBranch = 1;
                        cmdNew.Visible = true;
                    }
                    else
                    {
                        qsUEB = "SELECT TContID FROM tcontent WHERE ViewID='" + VID[0] + "' AND ViewParam='" + VPRM[0] + "' AND EditU LIKE ';%" + Session["UserName"].ToString() + ";%'";
                        dsUEB = GetData(qsUEB, "webbaseConnectionString");
                        if (dsUEB.Tables.Count > 0)
                        {
                            if (dsUEB.Tables[0].Rows.Count > 0)
                            {
                                UserEditBranch = 1;
                            }
                        }
                        QString = "SELECT DocID, DocType, DocHead, CIndex, NodeID, EditU, FileName FROM docs WHERE (EditU LIKE '%;" + Session["UserName"] + ";%' OR AccessU LIKE '%;guest;%' OR AccessG LIKE '%;Everyone;%' OR AccessG LIKE '%;Guests;%' OR AccessG LIKE '%;Authenticated users;%' " + Session["WhereGroups"] + ") AND DocType='" + VPRM[0] + "' ORDER BY CIndex";
                    }
                     */
                    if (Session["IsAdmin"].ToString() == "1")
                    {
                        cmdNew.Visible = true;
                        QString = "SELECT * FROM tcontent WHERE RecStatus=0 ORDER BY NodePath";
                    }
                    else
                    {
                        return;
                        //QString = "SELECT * FROM tcontent WHERE RecStatus=0 AND (EditU LIKE '%;" + Session["UserName"] + ";%' OR AccessU LIKE '%;guest;%' OR AccessG LIKE '%;Everyone;%' OR AccessG LIKE '%;Guests;%' OR AccessG LIKE '%;Authenticated users;%' " + Session["WhereGroups"] + ") ORDER BY NodePath";
                    }
                }
                ds = GFunc.GetData(QString, "WebCNS", false);
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        //DataRow row = ds.Tables[0].Rows[0];

                        foreach (DataRow row in ds.Tables[0].Rows)
                        {
                            H = null;
                            Label BkmListG = null;
                            NewRow = new TableRow();
                            if (row["EditU"].ToString().Contains(";" + Session["UserName"].ToString() + ";") | Session["IsAdmin"].ToString()=="1")
                            {
                                //if (Session["IsAdmin"].ToString() == "1")
                                //{
                                H = new Button();
                                H.Text = "Labot";
                                H.ID = "cmdEdit" + row["TContID"].ToString();
                                H.CssClass = "cmdEdit";
                                H.CommandArgument = row["TContID"].ToString();
                                H.PostBackUrl = "#pEdit";
                                H.Click += new EventHandler(H_Click);
                                BkmListG = new Label();
                                BkmListG.Text = "<a name=\"" + row["TContID"].ToString() + "\"></a>";
                                
                            }
                            NewCell = new TableCell();
                            //NewCell.Text = row["DocHead"].ToString();
                            if (H != null)
                            {
                                NewCell.Controls.Add(H);
                                NewCell.Controls.Add(BkmListG);
                            }
                            NewCell.Font.Bold = false;
                            NewCell.Font.Size = 10;
                            NewCell.VerticalAlign = VerticalAlign.Middle;
                            NewCell.HorizontalAlign = HorizontalAlign.Left;
                            NewCell.Width = Unit.Percentage(10);
                            NewRow.Cells.Add(NewCell);
                            //}

                            char sTab = '.';
                            string[] TCount;
                            string CellText;
                            TCount = row["NodePath"].ToString().Split('/');
                            //System.Web.UI.WebControls.hip
                            CellText = row["TContName"].ToString().PadLeft(row["TContName"].ToString().Length + TCount.GetLength(0), sTab);
                            //H.Text = row["CIndex"].ToString().Replace("/", ".") + "   " + row["DocHead"].ToString();

                            NewCell = new TableCell();
                            //NewCell.Text = row["DocHead"].ToString();
                            NewCell.Text = CellText;
                            NewCell.Font.Bold = false;
                            NewCell.Font.Size = 11;
                            NewCell.VerticalAlign = VerticalAlign.Middle;
                            NewCell.HorizontalAlign = HorizontalAlign.Left;
                            NewRow.Cells.Add(NewCell);
                            tblStruct.Rows.Add(NewRow);
                        }
                    }
                }

            //}
        }

        void H_Click(object sender, EventArgs e)
        {
            //pievienot rediģēšanas lauku aizpildīšanas kodu
            string Rec2Edit;
            string QString;
            DataSet ds;
            //int DelIndex;
            //atjaunojam sarakstus
            //dsGroups.ConnectionString = GFunc.GetConnectionString("WebCNS");
            gvAccessG.DataSource = GFunc.GetData("SELECT GroupName, Description FROM groups WHERE RecStatus=0 ORDER BY GroupName", "WebCNS", false);
            gvAccessG.DataBind();
            //dsUsers.ConnectionString = GFunc.GetConnectionString("WebCNS");
            gvAccessU.DataSource = GFunc.GetData("SELECT User, LongName FROM users WHERE RecStatus=0 ORDER BY User", "WebCNS", false);
            gvAccessU.DataBind();
            //dsViewID.ConnectionString = GFunc.GetConnectionString("WebCNS");
            ddlViewID.DataSource = GFunc.GetData("SELECT NosID, Nos FROM spr WHERE RecStatus=0 AND SprID='ViewID' ORDER BY Nos", "WebCNS", false);
            ddlViewID.DataBind();

            //pievienojam ddlSavePlace esošo ierakstu struktūru
            ddlSavePlace.Items.Clear();
            QString = "SELECT NodePath, TContName FROM tcontent WHERE RecStatus=0 ORDER BY NodePath";
            ds = GFunc.GetData(QString, "WebCNS", false);
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    //DataRow row = ds.Tables[0].Rows[0];

                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        char sTab = '.';
                        string[] TCount;
                        string CellText;
                        TCount = row["NodePath"].ToString().Split('/');
                        //System.Web.UI.WebControls.hip
                        CellText = row["TContName"].ToString().PadLeft(row["TContName"].ToString().Length + TCount.GetLength(0), sTab);
                        //H.Text = row["CIndex"].ToString().Replace("/", ".") + "   " + row["DocHead"].ToString();
                        ListItem LIPlace = new ListItem();
                        LIPlace.Text = CellText;
                        LIPlace.Value = row["NodePath"].ToString();
                        ddlSavePlace.Items.Add(LIPlace);

                    }
                }
            }
            /////////////////////////////////////////////////

            System.Web.UI.WebControls.Button b = sender as System.Web.UI.WebControls.Button;
            Rec2Edit = b.ID.Substring(7);
            QString = "SELECT * FROM tcontent WHERE RecStatus=0 AND TContID='" + Rec2Edit + "' ORDER BY NodePath";
            ds = GFunc.GetData(QString, "WebCNS", false);
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    txtTContID.Text = ds.Tables[0].Rows[0]["TContID"].ToString();
                    txtTContName.Text = ds.Tables[0].Rows[0]["TContName"].ToString();
                    txtViewParam.Text = ds.Tables[0].Rows[0]["ViewParam"].ToString();
                    txtLinkTbl.Text = ds.Tables[0].Rows[0]["LinkTbl"].ToString();
                    txtNodePath.Text = ds.Tables[0].Rows[0]["NodePath"].ToString();
                    txtNodeID.Text = ds.Tables[0].Rows[0]["NodeID"].ToString();
                    txtEditU.Text = ds.Tables[0].Rows[0]["EditU"].ToString();
                    txtAccessU.Text = ds.Tables[0].Rows[0]["AccessU"].ToString();
                    txtAccessG.Text = ds.Tables[0].Rows[0]["AccessG"].ToString();
                    ddlViewID.ClearSelection();
                    ddlSaveOpt.SelectedIndex = 1;
                    ddlSavePlace.SelectedValue = ds.Tables[0].Rows[0]["NodePath"].ToString();
                    ddlViewID.SelectedValue = ds.Tables[0].Rows[0]["ViewID"].ToString();
                    //ddlSavePlace.Items.Clear();
                    //ddlSavePlace.Items.Add("");
                }
            }
            cmdClose.PostBackUrl = "#" + b.CommandArgument;
            pEdit.Visible = true;
            //throw new NotImplementedException();
        }


        protected void cmdAccessU_Click(object sender, EventArgs e)
        {
            gvAccessU.Visible = !gvAccessU.Visible;
        }

        protected void cmdAccessG_Click(object sender, EventArgs e)
        {
            gvAccessG.Visible = !gvAccessG.Visible;
        }

        protected void cmdEditU_Click(object sender, EventArgs e)
        {
            gvEditU.Visible = !gvEditU.Visible;
        }

        protected void cmdNew_Click(object sender, EventArgs e)
        {
            //dsGroups.ConnectionString = GFunc.GetConnectionString("WebCNS");
            gvAccessG.DataSource = GFunc.GetData("SELECT GroupName, Description FROM groups WHERE RecStatus=0 ORDER BY GroupName", "WebCNS", false);
            gvAccessG.DataBind();
            //dsUsers.ConnectionString = GFunc.GetConnectionString("WebCNS");
            gvAccessU.DataSource = GFunc.GetData("SELECT User, LongName FROM users WHERE RecStatus=0 ORDER BY User", "WebCNS", false);
            gvAccessU.DataBind();
            //dsViewID.ConnectionString = GFunc.GetConnectionString("WebCNS");
            ddlViewID.DataSource = GFunc.GetData("SELECT NosID, Nos FROM spr WHERE RecStatus=0 AND SprID='ViewID' ORDER BY Nos", "WebCNS", false);
            ddlViewID.DataBind();

            txtTContID.Text = "";
            txtTContName.Text = "";
            txtViewParam.Text = "";
            txtLinkTbl.Text = "";
            txtNodePath.Text = "";
            txtNodeID.Text = "";
            txtEditU.Text = "";
            txtAccessU.Text = "";
            txtAccessG.Text = "";
            ddlViewID.ClearSelection();
            ddlSavePlace.ClearSelection();
            ddlSavePlace.Items.Clear();
            ddlSavePlace.Items.Add("");
            //pievienojam ddlSavePlace esošo ierakstu struktūru
            string QString = "SELECT NodePath, TContName FROM tcontent WHERE RecStatus=0 ORDER BY NodePath";
            DataSet ds = GFunc.GetData(QString, "WebCNS",false);
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    //DataRow row = ds.Tables[0].Rows[0];

                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        char sTab = '.';
                        string[] TCount;
                        string CellText;
                        TCount = row["NodePath"].ToString().Split('/');
                        //System.Web.UI.WebControls.hip
                        CellText = row["TContName"].ToString().PadLeft(row["TContName"].ToString().Length + TCount.GetLength(0), sTab);
                        //H.Text = row["CIndex"].ToString().Replace("/", ".") + "   " + row["DocHead"].ToString();
                        ListItem LIPlace = new ListItem();
                        LIPlace.Text = CellText;
                        LIPlace.Value = row["NodePath"].ToString();
                        ddlSavePlace.Items.Add(LIPlace);

                    }
                }
            }
            /////////////////////////////////////////////////
            pEdit.Visible = true;
        }

        protected void cmdClose_Click(object sender, EventArgs e)
        {
            lblErr.Text = "";
            pEdit.Visible = false;
            //this.Page_Load(sender, e);
            //this.cmdPostBack_Click(sender, e);
            //upList.Update();
        }

        protected void gvAccessU_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*txtAccessU.Text = txtAccessU.Text + ";" + gvAccessU.SelectedRow.Cells[1].Text + ";";
            txtAccessU.Text = txtAccessU.Text.Replace(";;", ";");
            txtAccessU.Focus();
            gvAccessU.Visible = false;
            */
            if (txtAccessU.Text.Contains(";" + gvAccessU.SelectedRow.Cells[1].Text + ";"))
            {
                txtAccessU.Text = txtAccessU.Text.Replace(";" + gvAccessU.SelectedRow.Cells[1].Text + ";", ";");
            }
            else
            {
                txtAccessU.Text = txtAccessU.Text + ";" + gvAccessU.SelectedRow.Cells[1].Text + ";";
                txtAccessU.Text = txtAccessU.Text.Replace(";;", ";");
            }

        }

        protected void gvAccessG_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*txtAccessG.Text = txtAccessG.Text + ";" + gvAccessG.SelectedRow.Cells[2].Text + ";";
            txtAccessG.Text = txtAccessG.Text.Replace(";;", ";");
            txtAccessG.Focus();
            gvAccessG.Visible = false;
             */
            if (txtAccessG.Text.Contains(";" + gvAccessG.SelectedRow.Cells[1].Text + ";"))
            {
                txtAccessG.Text = txtAccessG.Text.Replace(";" + gvAccessG.SelectedRow.Cells[1].Text + ";", ";");
            }
            else
            {
                txtAccessG.Text = txtAccessG.Text + ";" + gvAccessG.SelectedRow.Cells[1].Text + ";";
                txtAccessG.Text = txtAccessG.Text.Replace(";;", ";");
            }
        }

        protected void gvEditU_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*txtEditU.Text = txtEditU.Text + ";" + gvEditU.SelectedRow.Cells[1].Text + ";";
            txtEditU.Text = txtEditU.Text.Replace(";;", ";");
            txtEditU.Focus();
            gvEditU.Visible = false;
             */
            if (txtEditU.Text.Contains(";" + gvEditU.SelectedRow.Cells[1].Text + ";"))
            {
                txtEditU.Text = txtEditU.Text.Replace(";" + gvEditU.SelectedRow.Cells[1].Text + ";", ";");
            }
            else
            {
                txtEditU.Text = txtEditU.Text + ";" + gvEditU.SelectedRow.Cells[1].Text + ";";
                txtEditU.Text = txtEditU.Text.Replace(";;", ";");
            }
        }

        protected void cmdDel_Click(object sender, EventArgs e)
        {
            if (txtNodePath.Text.IndexOf("/") < 0)
            {
                lblErr.Text = "Pirmā līmeņa zaru dzēst nedrīkst.";
                return;
            }
            if (txtTContID.Text != string.Empty)
            {
                //pārbaudām vai ierakstam nav apakšnodaļas
                DataSet dsSubLev;
                int CountCI = 0;
                string QStr = "SELECT COUNT(NodePath) as CntCI FROM tcontent WHERE NodePath LIKE '" + txtNodePath.Text + "%'";
                dsSubLev = GFunc.GetData(QStr, "WebCNS", false);
                if (dsSubLev.Tables.Count > 0)
                {
                    if (dsSubLev.Tables[0].Rows.Count > 0)
                    {
                        DataRow SLRow = dsSubLev.Tables[0].Rows[0];
                        int.TryParse(SLRow["CntCI"].ToString(), out CountCI);
                        //ja ir atrasti vairāk ierakstu par 1, aizliedzam dzēst
                        if (CountCI > 1)
                        {
                            lblErr.Text = "Ierakstam ir piesaistītas apakšnodaļas! Apakšnodaļas jādzēš pirms ieraksta.";
                            return;
                        }
                    }
                }
                QStr = "DELETE FROM tcontent WHERE TContID='" + txtTContID.Text + "'";
                GFunc.GetData(QStr, "WebCNS", false);
            }
            //attīram laukus, lai lietotājs redzētu, ka dzēšana ir pabeigta
            txtTContID.Text = "";
            txtTContName.Text = "";
            txtViewParam.Text = "";
            txtLinkTbl.Text = "";
            txtNodePath.Text = "";
            txtNodeID.Text = "";
            txtEditU.Text = "";
            txtAccessU.Text = "";
            txtAccessG.Text = "";
            ddlViewID.ClearSelection();
            ddlSavePlace.ClearSelection();
            lblErr.Text = "Saita struktūras dati ir izdzēsti.";
            //ja aizveram formu uzreiz, saraksts tStruct neatjaunojas
            //pEdit.Visible = false;
            //cmdClose_Click(sender, e);
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            string QString = "";
            string[] c = new string[13];
            string StrFileList = "";
            int NewNodeID = 0;
            int NewLevel1 = 0;
            DataSet dsTemp;
            DataRow row;
            DataSet dsLID;
            string LID;
            int LastIndex;
            DataSet dsChild;

            try
            {
                lblErr.Text = "";

                if (ddlSavePlace.SelectedValue == string.Empty)
                {

                    if (txtTContID.Text == "")//jauns dokuments bez norādītas vietas - tiek pievienots kā norādītās grupas augstākā līmeņa pēdējais dokuments
                    {
                        //veidojam jaunu CIndex rindu
                        QString = "SELECT SUBSTRING_INDEX(NodePath,'/',1) as Level1, Max(SUBSTRING_INDEX(SUBSTRING_INDEX(NodePath,'/',2),'/',-1)+0) as Level2 FROM tcontent WHERE RecStatus=0 GROUP BY SUBSTRING_INDEX(NodePath,'/',1)";
                        dsTemp = GFunc.GetData(QString, "WebCNS", false);
                        if (dsTemp.Tables.Count > 0)
                        {
                            if (dsTemp.Tables[0].Rows.Count > 0)
                            {
                                row = dsTemp.Tables[0].Rows[0];
                                //ja norādītajā dok. grupā ir ieraksti, aprēķinam jauno indeksu pirmajā līmenī atstājot Level1, otrajā MAX+1
                                if (row["Level2"] != null)
                                {
                                    int.TryParse(row["Level2"].ToString(), out NewNodeID);
                                    NewNodeID += 1;

                                    txtNodeID.Text = NewNodeID.ToString();
                                    txtNodePath.Text = row["Level1"].ToString() + "/" + NewNodeID.ToString().PadLeft(3, '0');
                                }
                            }
                        }
                        if (NewNodeID == 0)//ja norādītajā dok. grupā nav ierakstu, pārbaudam vai vispār ir ieraksti
                        {
                            QString = "SELECT MAX(SUBSTRING_INDEX(NodePath,'/',1)+0) as Level1, 0 as Level2 FROM tcontent WHERE RecStatus=0";
                            dsTemp = GFunc.GetData(QString, "WebCNS", false);
                            if (dsTemp.Tables.Count > 0)
                            {
                                if (dsTemp.Tables[0].Rows.Count > 0)
                                {
                                    row = dsTemp.Tables[0].Rows[0];
                                    //ja ir ieraksti, aprēķinam jauno indeksu ņemot pirmajā līmenī MAX+1, otrajā 0+1
                                    if (row["Level1"] != null)
                                    {
                                        int.TryParse(row["Level2"].ToString(), out NewNodeID);
                                        NewNodeID += 1;
                                        int.TryParse(row["Level1"].ToString(), out NewLevel1);
                                        NewLevel1 += 1;
                                        txtNodeID.Text = NewNodeID.ToString();
                                        txtNodePath.Text = NewLevel1.ToString().PadLeft(3, '0') + "/" + NewNodeID.ToString().PadLeft(3, '0');
                                    }
                                }
                            }
                        }
                        if (NewNodeID == 0)//ja ierakstu nav vispār, aprēķinam jauno indeksu abos līmeņos sākot no 1
                        {
                            NewNodeID = 1;
                            NewLevel1 = 1;
                            txtNodeID.Text = NewNodeID.ToString();
                            txtNodePath.Text = NewLevel1.ToString().PadLeft(3, '0') + "/" + NewNodeID.ToString().PadLeft(3, '0');
                        }

                        c[0] = "TContID='" + GFunc.EscapeSQLCahrs(txtTContID.Text) + "'";
                        c[1] = "NodePath='" + GFunc.EscapeSQLCahrs(txtNodePath.Text) + "'";
                        c[2] = "NodeID='" + GFunc.EscapeSQLCahrs(txtNodeID.Text) + "'";
                        c[3] = "TContName='" + GFunc.EscapeSQLCahrs(txtTContName.Text) + "'";
                        c[4] = "ViewID='" + ddlViewID.SelectedValue + "'";
                        c[5] = "ViewParam='" + GFunc.EscapeSQLCahrs(txtViewParam.Text) + "'";
                        c[6] = "LinkTbl='" + GFunc.EscapeSQLCahrs(txtLinkTbl.Text) + "'";
                        c[7] = "AccessU='" + GFunc.EscapeSQLCahrs(txtAccessU.Text) + "'";
                        c[8] = "AccessG='" + GFunc.EscapeSQLCahrs(txtAccessG.Text) + "'";
                        c[9] = "EditU='" + GFunc.EscapeSQLCahrs(txtEditU.Text) + "'";
                        c[10] = "TimeAdd='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                        c[11] = "UserEdit='" + Session["UserName"].ToString() + "'";
                        c[12] = "UserAdd='" + Session["UserName"].ToString() + "'";

                        QString = "INSERT INTO tcontent SET " + c[1] + "," + c[2] + "," + c[3] + "," + c[4] + "," + c[5] + "," + c[6] + "," + c[7] + "," + c[8] + "," + c[9] + "," + c[10] + "," + c[11] + "," + c[12];
                        dsLID = GFunc.GetData(QString, "WebCNS", true);
                        LID = dsLID.Tables["tLID"].Rows[0]["LID"].ToString();
                        txtTContID.Text = LID;

                    }
                    else //esošs dokuments bez norādītas vietas
                    {
                        //aizvietojam esošo ierakstu pēc 'TContID' ar jauniem datiem
                        //katrs fails tiek saglabāts pie pievienošanas

                        c[0] = "TContID='" + GFunc.EscapeSQLCahrs(txtTContID.Text) + "'";
                        c[1] = "NodePath='" + GFunc.EscapeSQLCahrs(txtNodePath.Text) + "'";
                        c[2] = "NodeID='" + GFunc.EscapeSQLCahrs(txtNodeID.Text) + "'";
                        c[3] = "TContName='" + GFunc.EscapeSQLCahrs(txtTContName.Text) + "'";
                        c[4] = "ViewID='" + ddlViewID.SelectedValue + "'";
                        c[5] = "ViewParam='" + GFunc.EscapeSQLCahrs(txtViewParam.Text) + "'";
                        c[6] = "LinkTbl='" + GFunc.EscapeSQLCahrs(txtLinkTbl.Text) + "'";
                        c[7] = "AccessU='" + GFunc.EscapeSQLCahrs(txtAccessU.Text) + "'";
                        c[8] = "AccessG='" + GFunc.EscapeSQLCahrs(txtAccessG.Text) + "'";
                        c[9] = "EditU='" + GFunc.EscapeSQLCahrs(txtEditU.Text) + "'";
                        c[10] = "TimeAdd='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                        c[11] = "UserEdit='" + Session["UserName"].ToString() + "'";
                        //c[12] = "UserAdd='" + Session["UserName"].ToString() + "'";

                        QString = "UPDATE tcontent SET " + c[1] + "," + c[2] + "," + c[3] + "," + c[4] + "," + c[5] + "," + c[6] + "," + c[7] + "," + c[8] + "," + c[9] + "," + c[10] + "," + c[11] + " WHERE RecStatus=0 AND " + c[0];
                        GFunc.GetData(QString, "WebCNS", false);
                    }

                }
                else//ja vieta ir norādīta
                {
                    string CInd2Repl = "";
                    string NewCInd = "";
                    int NodeID2Repl;
                    int LevelCount;

                    switch (ddlSaveOpt.SelectedValue.ToString())
                    {
                        case "-1"://pirms
                            //saglabājam zara apakšlīmeņus ar esošajām NodePath
                            QString = "SELECT TContID, NodePath FROM tcontent WHERE RecStatus=0 AND NodePath LIKE '"+txtNodePath.Text+"/%'";
                            dsChild = GFunc.GetData(QString, "WebCNS", false);
                            //aprēķinam jauno 'NodePath' un 'NodeID' - tiek paņemti esošie no norādītā ieraksta
                            CInd2Repl = ddlSavePlace.SelectedValue.ToString();
                            //pārbaudam vai aizvietojamais zars nav root līmenī
                            if (CInd2Repl.IndexOf("/") < 0)
                            {
                                lblErr.Text = "Pirms pirmā līmeņa zara pievienot jaunus līmeņus nedrīkst.";
                                return;
                            } 
                            NewCInd = CInd2Repl;
                            int.TryParse(CInd2Repl.Substring(CInd2Repl.LastIndexOf("/") + 1), out NodeID2Repl);
                            NewNodeID = NodeID2Repl;
                            //aprēķinam līmeņu skaitu jaunajā 'CIndex'
                            LevelCount = NewCInd.Split('/').GetLength(0);
                            //palielinam 'CIndex' zaru par 1 uz leju no norādītā
                            QString = "UPDATE tcontent SET NodePath=CONCAT(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "-1),'/',LPAD(SUBSTRING_INDEX(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "),'/',-1)+1,3,'0'),RIGHT(NodePath,LENGTH(NodePath) -( LENGTH(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "-1))+LENGTH(SUBSTRING_INDEX(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "),'/',-1)))-1)), NodeID=SUBSTRING_INDEX(NodePath,'/',-1) WHERE RecStatus=0 AND SUBSTRING_INDEX(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "),'/',-1)+0 >=SUBSTRING_INDEX('" + NewCInd + "','/',-1)+0 AND NodePath LIKE CONCAT(SUBSTRING_INDEX('" + NewCInd + "','/'," + LevelCount.ToString() + "-1),'/','%')";
                            GFunc.GetData(QString, "WebCNS", false);
                            //pievienajam jaunu ierakstu ar veco indeksu
                            //c[0] = "DocID='" + txtDocID.Text + "'"; - tiek izveidots jauns
                            c[0] = "TContID='" + GFunc.EscapeSQLCahrs(txtTContID.Text) + "'";
                            c[1] = "NodePath='" + NewCInd + "'";
                            c[2] = "NodeID='" + NewNodeID.ToString("000") + "'";
                            c[3] = "TContName='" + GFunc.EscapeSQLCahrs(txtTContName.Text) + "'";
                            c[4] = "ViewID='" + ddlViewID.SelectedValue + "'";
                            c[5] = "ViewParam='" + GFunc.EscapeSQLCahrs(txtViewParam.Text) + "'";
                            c[6] = "LinkTbl='" + GFunc.EscapeSQLCahrs(txtLinkTbl.Text) + "'";
                            c[7] = "AccessU='" + GFunc.EscapeSQLCahrs(txtAccessU.Text) + "'";
                            c[8] = "AccessG='" + GFunc.EscapeSQLCahrs(txtAccessG.Text) + "'";
                            c[9] = "EditU='" + GFunc.EscapeSQLCahrs(txtEditU.Text) + "'";
                            c[10] = "TimeAdd='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                            c[11] = "UserEdit='" + Session["UserName"].ToString() + "'";
                            c[12] = "UserAdd='" + Session["UserName"].ToString() + "'";

                            QString = "INSERT INTO tcontent SET " + c[1] + "," + c[2] + "," + c[3] + "," + c[4] + "," + c[5] + "," + c[6] + "," + c[7] + "," + c[8] + "," + c[9] + "," + c[10] + "," + c[11] + "," + c[12];
                            dsLID = GFunc.GetData(QString, "WebCNS", true);

                            //ja šis nav jauns ieraksts, dzēšam to no datubāzes pēc TContID
                            if (txtTContID.Text != string.Empty)
                            {
                                QString = "DELETE FROM tcontent WHERE TContID='" + txtTContID.Text + "'";
                                GFunc.GetData(QString, "WebCNS", false);
                            }
                            //iepriekš saglabātajiem apakšlīmeņiem nomainam veco NodePath uz jauno
                            if (dsChild.Tables.Count > 0)
                            {
                                if (dsChild.Tables[0].Rows.Count > 0)
                                {
                                    foreach (DataRow rowCh in dsChild.Tables[0].Rows)
                                    {
                                        string ContID = rowCh["TContID"].ToString();
                                        string OldNodePath = rowCh["NodePath"].ToString();
                                        string NewNodePath = OldNodePath.Substring(txtNodePath.Text.Length);
                                        NewNodePath = NewCInd + NewNodePath;
                                        QString = "UPDATE tcontent SET NodePath='" + NewNodePath + "' WHERE TContID=" + ContID + "";
                                        GFunc.GetData(QString, "WebCNS", false);

                                    }
                                }
                            }
                        //aizpildam laukus ar jaunajām vērtībām
                            txtNodePath.Text = NewCInd;
                            txtNodeID.Text = NewNodeID.ToString();
                            LID = dsLID.Tables["tLID"].Rows[0]["LID"].ToString();
                            txtTContID.Text = LID;
                            break;
                        case "0"://aizvietot
                            CInd2Repl = ddlSavePlace.SelectedValue.ToString();
                            //pārbaudam vai aizvietojamais zars nav root līmenī
                            if (CInd2Repl.IndexOf("/") < 0 & txtNodePath.Text.IndexOf("/")>0)
                            {
                                lblErr.Text = "Pirmā līmeņa zaru aizvietot ar zemāka līmeņa zaru nedrīkst.";
                                return;
                            } 
                            if (CInd2Repl.LastIndexOf("/") > 0)
                            {
                                int.TryParse(CInd2Repl.Substring(CInd2Repl.LastIndexOf("/")), out NodeID2Repl);
                            }
                            else
                            {
                                int.TryParse(CInd2Repl, out NodeID2Repl);
                            }
                            //aizvietojam norādīto ierakstu ar šo pēc 'NodePath'

                            //c[0] = "TContID='" + GFunc.EscapeSQLCahrs(txtTContID.Text) + "'"; - paliek no iepriekšējā ieraksta
                            c[1] = "NodePath='" + CInd2Repl + "'";
                            //c[2] = "NodeID='" + NewNodeID.ToString("000") + "'"; - paliek no iepriekšējā ieraksta
                            c[3] = "TContName='" + GFunc.EscapeSQLCahrs(txtTContName.Text) + "'";
                            c[4] = "ViewID='" + ddlViewID.SelectedValue + "'";
                            c[5] = "ViewParam='" + GFunc.EscapeSQLCahrs(txtViewParam.Text) + "'";
                            c[6] = "LinkTbl='" + GFunc.EscapeSQLCahrs(txtLinkTbl.Text) + "'";
                            c[7] = "AccessU='" + GFunc.EscapeSQLCahrs(txtAccessU.Text) + "'";
                            c[8] = "AccessG='" + GFunc.EscapeSQLCahrs(txtAccessG.Text) + "'";
                            c[9] = "EditU='" + GFunc.EscapeSQLCahrs(txtEditU.Text) + "'";
                            c[10] = "TimeAdd='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                            c[11] = "UserEdit='" + Session["UserName"].ToString() + "'";

                            QString = "UPDATE tcontent SET " + c[3] + "," + c[4] + "," + c[5] + "," + c[6] + "," + c[7] + "," + c[8] + "," + c[9] + "," + c[10] + "," + c[11] + " WHERE RecStatus=0 AND " + c[1];
                            GFunc.GetData(QString, "WebCNS", false);

                            //ja šis nav jauns ieraksts, dzēšam to no datubāzes pēc TContID
                            //un netiek labots tas past ieraksts
                            if (txtTContID.Text != string.Empty & CInd2Repl!=txtNodePath.Text)
                            {
                                QString = "DELETE FROM tcontent WHERE TContID='" + txtTContID.Text + "'";
                                GFunc.GetData(QString, "WebCNS", false);
                            }
                            //aizpildam laukus ar jaunajām vērtībām
                            txtNodePath.Text = CInd2Repl;
                            txtNodeID.Text = NodeID2Repl.ToString();
                            QString = "SELECT TContID FROM tcontent WHERE NodePath='" + CInd2Repl + "' AND RecStatus=0";
                            dsLID = GFunc.GetData(QString, "WebCNS", false);
                            if (dsLID.Tables.Count > 0)
                            {
                                if (dsLID.Tables[0].Rows.Count > 0)
                                {
                                    LID = dsLID.Tables[0].Rows[0]["TContID"].ToString();
                                    txtTContID.Text = LID;
                                }
                                else
                                    txtTContID.Text = "";
                            }
                            else
                                txtTContID.Text = "";
                            break;
                        case "1"://pēc
                            //saglabājam zara apakšlīmeņus ar esošajām NodePath
                            QString = "SELECT TContID, NodePath FROM tcontent WHERE RecStatus=0 AND NodePath LIKE '" + txtNodePath.Text + "/%'";
                            dsChild = GFunc.GetData(QString, "WebCNS", false);
                            //aprēķinam jauno 'NodePath' un 'NodeID' - tiek paņemti esošie no norādītā ieraksta
                            CInd2Repl = ddlSavePlace.SelectedValue.ToString();
                            //pārbaudam vai aizvietojamais zars nav root līmenī
                            if (CInd2Repl.IndexOf("/") < 0)
                            {
                                lblErr.Text = "Pēc pirmā līmeņa zara pievienot jaunus zarus drīkst tikai kā apakšlīmeņus.";
                                return;
                            } 
                            int.TryParse(CInd2Repl.Substring(CInd2Repl.LastIndexOf("/") + 1), out LastIndex);
                            LastIndex += 1;
                            CInd2Repl = CInd2Repl.Remove(CInd2Repl.LastIndexOf("/") + 1);
                            CInd2Repl = CInd2Repl + LastIndex.ToString().PadLeft(3, '0');
                            NewCInd = CInd2Repl;
                            int.TryParse(CInd2Repl.Substring(CInd2Repl.LastIndexOf("/") + 1), out NodeID2Repl);
                            NewNodeID = NodeID2Repl;
                            //aprēķinam līmeņu skaitu jaunajā 'CIndex'
                            LevelCount = NewCInd.Split('/').GetLength(0);
                            //palielinam 'CIndex' zaru par 1 uz leju no norādītā
                            QString = "UPDATE tcontent SET NodePath=CONCAT(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "-1),'/',LPAD(SUBSTRING_INDEX(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "),'/',-1)+1,3,'0'),RIGHT(NodePath,LENGTH(NodePath) -( LENGTH(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "-1))+LENGTH(SUBSTRING_INDEX(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "),'/',-1)))-1)), NodeID=SUBSTRING_INDEX(NodePath,'/',-1) WHERE RecStatus=0 AND SUBSTRING_INDEX(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "),'/',-1)+0 >=SUBSTRING_INDEX('" + NewCInd + "','/',-1)+0 AND NodePath LIKE CONCAT(SUBSTRING_INDEX('" + NewCInd + "','/'," + LevelCount.ToString() + "-1),'/','%')";
                            GFunc.GetData(QString, "WebCNS", false);
                            //pievienajam jaunu ierakstu ar veco indeksu
                            //c[0] = "TContID='" + GFunc.EscapeSQLCahrs(txtTContID.Text) + "'"; - tiek izveidots jauns
                            c[1] = "NodePath='" + NewCInd + "'";
                            c[2] = "NodeID='" + NewNodeID.ToString("000") + "'";
                            c[3] = "TContName='" + GFunc.EscapeSQLCahrs(txtTContName.Text) + "'";
                            c[4] = "ViewID='" + ddlViewID.SelectedValue + "'";
                            c[5] = "ViewParam='" + GFunc.EscapeSQLCahrs(txtViewParam.Text) + "'";
                            c[6] = "LinkTbl='" + GFunc.EscapeSQLCahrs(txtLinkTbl.Text) + "'";
                            c[7] = "AccessU='" + GFunc.EscapeSQLCahrs(txtAccessU.Text) + "'";
                            c[8] = "AccessG='" + GFunc.EscapeSQLCahrs(txtAccessG.Text) + "'";
                            c[9] = "EditU='" + GFunc.EscapeSQLCahrs(txtEditU.Text) + "'";
                            c[10] = "TimeAdd='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                            c[11] = "UserEdit='" + Session["UserName"].ToString() + "'";
                            c[12] = "UserAdd='" + Session["UserName"].ToString() + "'";

                            QString = "INSERT INTO tcontent SET " + c[1] + "," + c[2] + "," + c[3] + "," + c[4] + "," + c[5] + "," + c[6] + "," + c[7] + "," + c[8] + "," + c[9] + "," + c[10] + "," + c[11] + "," + c[12];
                            dsLID = GFunc.GetData(QString, "WebCNS", true);

                            //ja šis nav jauns ieraksts, dzēšam to no datubāzes pēc DocID
                            if (txtTContID.Text != string.Empty)
                            {
                                QString = "DELETE FROM tcontent WHERE TContID='" + txtTContID.Text + "'";
                                GFunc.GetData(QString, "WebCNS", false);
                            }
                            //iepriekš saglabātajiem apakšlīmeņiem nomainam veco NodePath uz jauno
                            if (dsChild.Tables.Count > 0)
                            {
                                if (dsChild.Tables[0].Rows.Count > 0)
                                {
                                    foreach (DataRow rowCh in dsChild.Tables[0].Rows)
                                    {
                                        string ContID = rowCh["TContID"].ToString();
                                        string OldNodePath = rowCh["NodePath"].ToString();
                                        string NewNodePath = OldNodePath.Substring(txtNodePath.Text.Length);
                                        NewNodePath = NewCInd + NewNodePath;
                                        QString = "UPDATE tcontent SET NodePath='" + NewNodePath + "' WHERE TContID=" + ContID + "";
                                        GFunc.GetData(QString, "WebCNS", false);

                                    }
                                }
                            }
                            //aizpildam laukus ar jaunajām vērtībām
                            txtNodePath.Text = NewCInd;
                            txtNodeID.Text = NewNodeID.ToString("000");
                            LID = dsLID.Tables["tLID"].Rows[0]["LID"].ToString();
                            txtTContID.Text = LID;
                            break;
                        case "2"://kā apakšnodaļa
                            //saglabājam zara apakšlīmeņus ar esošajām NodePath
                            QString = "SELECT TContID, NodePath FROM tcontent WHERE RecStatus=0 AND NodePath LIKE '" + txtNodePath.Text + "/%'";
                            dsChild = GFunc.GetData(QString, "WebCNS", false);
                            //aprēķinam jauno 'NodePath' un 'NodeID' - tiek paņemti esošie no norādītā ieraksta
                            CInd2Repl = ddlSavePlace.SelectedValue.ToString();
                            //int.TryParse(CInd2Repl.Substring(CInd2Repl.LastIndexOf("/") + 1), out LastIndex);
                            LastIndex = 1;
                            //CInd2Repl = CInd2Repl.Remove(CInd2Repl.LastIndexOf("/") + 1);
                            CInd2Repl = CInd2Repl + "/" + LastIndex.ToString().PadLeft(3, '0');
                            NewCInd = CInd2Repl;
                            int.TryParse(CInd2Repl.Substring(CInd2Repl.LastIndexOf("/") + 1), out NodeID2Repl);
                            NewNodeID = NodeID2Repl;
                            //aprēķinam līmeņu skaitu jaunajā 'CIndex'
                            LevelCount = NewCInd.Split('/').GetLength(0);
                            //palielinam 'CIndex' zaru par 1 uz leju no norādītā
                            QString = "UPDATE tcontent SET NodePath=CONCAT(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "-1),'/',LPAD(SUBSTRING_INDEX(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "),'/',-1)+1,3,'0'),RIGHT(NodePath,LENGTH(NodePath) -( LENGTH(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "-1))+LENGTH(SUBSTRING_INDEX(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "),'/',-1)))-1)), NodeID=SUBSTRING_INDEX(NodePath,'/',-1) WHERE RecStatus=0 AND SUBSTRING_INDEX(SUBSTRING_INDEX(NodePath,'/'," + LevelCount.ToString() + "),'/',-1)+0 >=SUBSTRING_INDEX('" + NewCInd + "','/',-1)+0 AND NodePath LIKE CONCAT(SUBSTRING_INDEX('" + NewCInd + "','/'," + LevelCount.ToString() + "-1),'/','%')";
                            GFunc.GetData(QString, "WebCNS", false);
                            //pievienajam jaunu ierakstu ar veco indeksu
                            //c[0] = "TContID='" + GFunc.EscapeSQLCahrs(txtTContID.Text) + "'"; - tiek izveidots jauns
                            c[1] = "NodePath='" + NewCInd + "'";
                            c[2] = "NodeID='" + NewNodeID.ToString("000") + "'";
                            c[3] = "TContName='" + GFunc.EscapeSQLCahrs(txtTContName.Text) + "'";
                            c[4] = "ViewID='" + ddlViewID.SelectedValue + "'";
                            c[5] = "ViewParam='" + GFunc.EscapeSQLCahrs(txtViewParam.Text) + "'";
                            c[6] = "LinkTbl='" + GFunc.EscapeSQLCahrs(txtLinkTbl.Text) + "'";
                            c[7] = "AccessU='" + GFunc.EscapeSQLCahrs(txtAccessU.Text) + "'";
                            c[8] = "AccessG='" + GFunc.EscapeSQLCahrs(txtAccessG.Text) + "'";
                            c[9] = "EditU='" + GFunc.EscapeSQLCahrs(txtEditU.Text) + "'";
                            c[10] = "TimeAdd='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                            c[11] = "UserEdit='" + Session["UserName"].ToString() + "'";
                            c[12] = "UserAdd='" + Session["UserName"].ToString() + "'";

                            QString = "INSERT INTO tcontent SET " + c[1] + "," + c[2] + "," + c[3] + "," + c[4] + "," + c[5] + "," + c[6] + "," + c[7] + "," + c[8] + "," + c[9] + "," + c[10] + "," + c[11] + "," + c[12];
                            dsLID = GFunc.GetData(QString, "WebCNS", true);

                            //ja šis nav jauns ieraksts, dzēšam to no datubāzes pēc DocID
                            if (txtTContID.Text != string.Empty)
                            {
                                QString = "DELETE FROM tcontent WHERE TContID='" + txtTContID.Text + "'";
                                GFunc.GetData(QString, "WebCNS", false);
                            }
                            //iepriekš saglabātajiem apakšlīmeņiem nomainam veco NodePath uz jauno
                            if (dsChild.Tables.Count > 0)
                            {
                                if (dsChild.Tables[0].Rows.Count > 0)
                                {
                                    foreach (DataRow rowCh in dsChild.Tables[0].Rows)
                                    {
                                        string ContID = rowCh["TContID"].ToString();
                                        string OldNodePath = rowCh["NodePath"].ToString();
                                        string NewNodePath = OldNodePath.Substring(txtNodePath.Text.Length);
                                        NewNodePath = NewCInd + NewNodePath;
                                        QString = "UPDATE tcontent SET NodePath='" + NewNodePath + "' WHERE TContID=" + ContID + "";
                                        GFunc.GetData(QString, "WebCNS", false);

                                    }
                                }
                            }
                            //aizpildam laukus ar jaunajām vērtībām
                            txtNodePath.Text = NewCInd;
                            txtNodeID.Text = NewNodeID.ToString();
                            LID = dsLID.Tables["tLID"].Rows[0]["LID"].ToString();
                            txtTContID.Text = LID;

                            break;
                        default:
                            break;
                    }


                }
                lblErr.Text = "Saita struktūras dati ir saglabāti.";
                //GetFileList(txtDocID.Text);
            }
            catch (Exception ex)
            {
                lblErr.Text = ex.Message;
            }

        }

        protected void cmdPostBack_Click(object sender, EventArgs e)
        {
            //test
        }


    }
}
